package com.example.mobile2032021606168xmy0521classtest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    RecyclerView rvMainNews;
    String url = "http://192.168.29.230:3000/news";
   OkHttpClient okHttpClient=new OkHttpClient();
   Gson gson=new Gson();
   Type type =new TypeToken<List<News>>(){}.getType();
   List<News> newsList=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rvMainNews = findViewById(R.id.rvMainNews);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request=new Request.Builder()
                        .url(url)
                        .build();
                Call call=okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String result=response.body().string();
                        newsList=gson.fromJson(result,type);
                        Log.i("TAG","onResponse:"+newsList.get(0).getTitle());

                    }
                });

            }
        }).start();
    }
}